<template>
	<view class="container">
		<view class="header">
			<view class="title">我的收藏</view>
			<view class="header-actions">
				<button class="action-btn" 
					@click="clearFavorites" 
					:disabled="favorites.length === 0"
					:class="{ 'disabled': favorites.length === 0 }"
				>清空收藏夹</button>
			</view>
		</view>
		
		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
		
		<view v-else-if="favorites.length === 0" class="empty">
			<text>收藏夹是空的，快去收藏喜欢的商品吧！</text>
		</view>
		
		<view v-else class="favorites-list">
			<view v-for="item in favorites" :key="item.id" class="favorite-item" @click="goToDetail(item.commodity.id)">
				<image 
					:src="getImgUrl(item.commodity.image && item.commodity.image.length > 0 ? item.commodity.image[0] : '')" 
					class="commodity-image"
					mode="aspectFill"
				></image>
				<view class="commodity-info">
					<text class="commodity-name">{{ item.commodity.name }}</text>
					<text class="commodity-price">¥{{ item.commodity.price }}</text>
					<view class="commodity-tags">
						<text v-for="(tag, index) in item.commodity.categoryTag" :key="index" class="commodity-tag">
							{{ tag }}
						</text>
					</view>
				</view>
				<view class="action-wrapper" @click.stop="removeFavorite(item.commodityId)">
					<text class="iconfont icon-delete"></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { SERVER_BASE_URL } from '@/utils/request';
import http from '@/utils/request';

export default {
	data() {
		return {
			favorites: [],
			loading: false,
			userId: null,
			serverBaseUrl: SERVER_BASE_URL
		};
	},
	onLoad() {
		this.checkLoginStatus();
	},
	onShow() {
		this.getFavoritesList();
	},
	// 启用下拉刷新
	onPullDownRefresh() {
		this.getFavoritesList(() => {
			uni.stopPullDownRefresh();
		});
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const userStr = uni.getStorageSync('user');
			if (userStr) {
				try {
					const userInfo = JSON.parse(userStr);
					if (userInfo && userInfo.id) {
						this.userId = userInfo.id;
						return true;
					}
				} catch (error) {
					console.error('解析用户信息失败', error);
				}
			}
			
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1500);
			
			return false;
		},
		
		// 获取收藏列表
		async getFavoritesList(callback) {
			if (!this.checkLoginStatus()) return;
			
			this.loading = true;
			try {
				const response = await http.get('/favorites/list');
				
				if (response.code === 200) {
					this.favorites = response.data;
				} else {
					uni.showToast({
						title: response.message || '获取收藏夹失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取收藏夹失败:', error);
				uni.showToast({
					title: '获取收藏夹失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				if (typeof callback === 'function') {
					callback();
				}
			}
		},
		
		// 取消收藏
		async removeFavorite(commodityId) {
			try {
				const response = await http.delete('/favorites/remove', {
					params: { commodityId }
				});
				
				if (response.code === 200) {
					uni.showToast({
						title: '取消收藏成功',
						icon: 'success'
					});
					// 更新本地数据
					this.favorites = this.favorites.filter(
						item => item.commodityId !== commodityId
					);
				} else {
					uni.showToast({
						title: response.message || '取消收藏失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('取消收藏失败:', error);
				uni.showToast({
					title: '取消收藏失败',
					icon: 'none'
				});
			}
		},
		
		// 清空收藏夹
		clearFavorites() {
			if (!this.checkLoginStatus() || this.favorites.length === 0) return;
			
			uni.showModal({
				title: '提示',
				content: '确定要清空收藏夹吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await http.delete('/favorites/clear');
							
							if (response.code === 200) {
								this.favorites = [];
								uni.showToast({
									title: '清空成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: response.message || '清空失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('清空失败:', error);
							uni.showToast({
								title: '清空失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 跳转到商品详情页
		goToDetail(id) {
			uni.navigateTo({
				url: `/pages/detail/detail?id=${id}`
			});
		},
		
		// 处理图片URL
		getImgUrl(url) {
			if (!url) return '/static/icons/no-image.png';
			
			// 确保有服务器地址前缀
			let fullUrl = url;
			if (url.startsWith('/uploads/')) {
				fullUrl = this.serverBaseUrl + url;
			}
			
			return fullUrl;
		}
	}
};
</script>

<style>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding: 30rpx;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.title {
	font-size: 34rpx;
	font-weight: bold;
	color: #333;
}

.header-actions {
	display: flex;
}

.action-btn {
	background-color: #F56C6C;
	color: #fff;
	font-size: 24rpx;
	padding: 8rpx 20rpx;
	border-radius: 30rpx;
	margin-left: 10rpx;
	line-height: 1.5;
	height: auto;
}

.action-btn.disabled {
	background-color: #ccc;
	color: #fff;
}

.loading, .empty {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 30rpx;
}

.favorites-list {
	padding-bottom: 30rpx;
}

.favorite-item {
	display: flex;
	background-color: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
	position: relative;
}

.commodity-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
	background-color: #f5f5f5;
}

.commodity-info {
	flex: 1;
	margin-left: 20rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.commodity-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	line-height: 1.4;
	margin-bottom: 10rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.commodity-price {
	font-size: 32rpx;
	color: #F56C6C;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.commodity-tags {
	display: flex;
	flex-wrap: wrap;
}

.commodity-tag {
	background-color: #F2F6FC;
	color: #409EFF;
	font-size: 20rpx;
	padding: 4rpx 16rpx;
	border-radius: 20rpx;
	margin-right: 10rpx;
	margin-bottom: 10rpx;
}

.action-wrapper {
	position: absolute;
	top: 20rpx;
	right: 20rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.action-wrapper .iconfont {
	font-size: 40rpx;
	color: #F56C6C;
}
</style> 